<?php

namespace addons\csmitsm\library\xcore\xcflow\utils;

use addons\csmitsm\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmitsm\library\sdnode\xstack\utils\XsJsonUtils;
use addons\csmitsm\library\sdnode\xstack\utils\XsStringUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;


class DevXcformFieldsUtils
{

    /**
     * DevXcformFieldsUtils::replaceDbtablePrefix("fa_csmitsm_xcflowdbview",["viewname"],["fieldjson"]);
     * @return void
     */
    public static function replaceDbtablePrefix($tablename, $fullFields, $contentFields){
        $list = XcDatabaseUtils::getListBySql($tablename, []);
        foreach($list as $item){
            $toSaveModel = [];
            foreach($fullFields as $field){
                $newValue = XcDatabaseUtils::getAbstraceTablename($item[$field]);
                $newValue = XsStringUtils::replace($newValue, "__prefix__", "__PREFIX__");
                $toSaveModel[$field] = $newValue;
            }

            foreach($contentFields as $field){
                $replace = "__PREFIX__";
                $search = "fa_";
                $newValue = preg_replace("/" . preg_quote($search, "/") . "/i", $replace, $item[$field]);
                $newValue = XsStringUtils::replace($newValue, "__prefix__", "__PREFIX__");
                
                $toSaveModel[$field] = $newValue;
            }

            // $i = 0;
            XcDatabaseUtils::save($tablename, $item['id'], $toSaveModel);
        }


        
    }

    /**
     * insertSystemTableToMdm([["fa_admin","nickname"]]);
     * @return void
     */
    public static function insertSystemTableToMdm($tables)
    {
        $dao = new \app\admin\model\csmitsm\Xcflowmdm();
        foreach ($tables as $table) {
            $noprefixtablename = XcDatabaseUtils::getNoprefixTablename($table[0]);
            $tablename = "__PREFIX__" . $noprefixtablename;
            $mdm = XcDaoUtils::getRowBySql($dao, [["publishtablename", "=", $tablename]]);

            $toSaveModel = null;
            if (true) {
                $tableinfo = XcDatabaseUtils::getTableInfo($tablename);
                $tablecomment = $tableinfo["comment"];

                $fields = XcDatabaseUtils::queryTablefieldList($tablename);
                $array = [];
                foreach ($fields as $field) {
                    $array[] = DevXcformFieldsUtils::generateXcfieldjson($field);
                }
                $xcfieldjson = "[" . join(',', $array) . "]";
                $toSaveModel = [
                    "xcformtype" => "mdm",
                    "code" => $noprefixtablename,
                    "name" => "{$tablecomment}(系统表)",
                    'xcfieldjson' => $xcfieldjson,
                    'displayfieldcode' => $table[1],
                    'haspublish' => "Y",
                    'publishtablename' => $tablename,
                    'status' => 'normal',
                    'type' => 'system_table',
                    'weigh' => 0,
                ];
            }

            if ($mdm == null) {
                XcDaoUtils::create($dao, $toSaveModel);
            } else {
                $mdm->save($toSaveModel);
            }
        }
    }

    public static function getFaFieldtype($fieldcode, $fieldtype, $fieldtitle)
    {
        $faFieldtype = $fieldcode;
        if (XsStringUtils::endsWith($fieldcode, "admin_id")) {
            $faFieldtype = "admin_id";
        } else if (XsStringUtils::endsWith($fieldcode, "role_id")) {
            $faFieldtype = "role_id";
        } else if (XsStringUtils::endsWith($fieldcode, "images")) {
            $faFieldtype = "images";
        } else if (XsStringUtils::endsWith($fieldcode, "image")) {
            $faFieldtype = "image";
        } else if (XsStringUtils::endsWith($fieldcode, "avatar")) {
            $faFieldtype = "image";
        }


        return $faFieldtype;
    }

    public static function generateXcfieldjson($field)
    {
        $result = null;

        $fieldcode = $field['name'];
        $fieldtype = $field['fieldtype'];
        $fieldtitle = $field['comment'];

        $faFieldtype = static::getFaFieldtype($fieldcode, $fieldtype, $fieldtitle);
        switch ($faFieldtype) {
            case "image":
            case "images":
                $fieldtag = "xcform_control_input_upload";
                $result = [
                    'type' => 'system_field',
                    'title' => $fieldtitle,
                    'fieldcode' => $fieldcode,
                    'fieldtag' => $fieldtag,
                    'fieldjson' => XsJsonUtils::jsonToString([
                        "__vModel__" => $fieldcode,
                        "__config__" => [
                            "tag" => $fieldtag
                        ],
                        "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                        "xcform_base_xctitle" => ["value" => $fieldtitle],
                        "xcform_prop_hidden" => ["value" => true],
                        "xcform_base_property_input_upload" => ["displayMethod" => 'picture', "acceptFileTypes" => ["image"]],
                    ])
                ];
                break;
            case "role_id":
                $fieldtag = "xcform_control_objselect";
                $result = [
                    'type' => 'system_field',
                    'title' => $fieldtitle,
                    'fieldcode' => $fieldcode,
                    'fieldtag' => $fieldtag,
                    'fieldjson' => XsJsonUtils::jsonToString([
                        "__vModel__" => $fieldcode,
                        "__config__" => [
                            "tag" => $fieldtag
                        ],
                        "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                        "xcform_base_xctitle" => ["value" => $fieldtitle],
                        "xcform_prop_hidden" => ["value" => true],
                        "xcform_base_selecttablefield" => ["tablename" => '__PREFIX__auth_group', "showfields" => ["name"], "filterfields" => ["name"]],
                    ])
                ];
                break;
            case "admin_id":
                $fieldtag = "xcform_control_objselect";
                $result = [
                    'type' => 'system_field',
                    'title' => $fieldtitle,
                    'fieldcode' => $fieldcode,
                    'fieldtag' => $fieldtag,
                    'fieldjson' => XsJsonUtils::jsonToString([
                        "__vModel__" => $fieldcode,
                        "__config__" => [
                            "tag" => $fieldtag
                        ],
                        "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                        "xcform_base_xctitle" => ["value" => $fieldtitle],
                        "xcform_prop_hidden" => ["value" => true],
                        "xcform_base_selecttablefield" => ["tablename" => '__PREFIX__admin', "showfields" => ["nickname"], "filterfields" => ["nickname", "username"]],
                    ])
                ];
                break;
            case "createtime":
            case "updatetime":
                $fieldtag = "xcform_control_input_datetime";
                $result = [
                    'type' => 'system_field',
                    'title' => $fieldtitle,
                    'fieldcode' => $fieldcode,
                    'fieldtag' => $fieldtag,
                    'fieldjson' => XsJsonUtils::jsonToString([
                        "__vModel__" => $fieldcode,
                        "__config__" => [
                            "tag" => $fieldtag
                        ],
                        "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                        "xcform_base_xctitle" => ["value" => $fieldtitle],
                        "xcform_prop_hidden" => ["value" => true],
                        "xcform_base_property_input_datetime" => ["format" => 'yyyy-MM-dd HH:mm'],
                    ])
                ];
            default:
                $fieldtag = "xcform_control_input_string";
                $result = [
                    'type' => 'system_field',
                    'title' => $fieldtitle,
                    'fieldcode' => $fieldcode,
                    'fieldtag' => $fieldtag,
                    'fieldjson' => XsJsonUtils::jsonToString([
                        "__vModel__" => $fieldcode,
                        "__config__" => [
                            "tag" => $fieldtag
                        ],
                        "xcform_base_inputfieldcode" => ["value" => $fieldcode],
                        "xcform_base_xctitle" => ["value" => $fieldtitle],
                        "xcform_prop_hidden" => ["value" => true],
                    ])
                ];
        }
        return XsJsonUtils::jsonToString($result);
    }
}
